//
//  TitleNumberCell.m
//  MoneyIndividual
//
//  Created by Tai Le on 12/30/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "TitleNumberCell.h"
#import "CalculatorView.h"

@implementation TitleNumberCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.textField.keyboardType = UIKeyboardTypeNumberPad;
        
        [self initializeAccessoryView];
    }
    
    return self;
}

- (void)initializeAccessoryView
{
    _calculartorView = [[CalculatorView alloc] initWithTextField:self.textField];
    _calculartorView.calculatorDelegate = self;
    _calculartorView.frame = RECT(0, self.toolbar.bottom, SCREEN_SIZE.width, HEI_HEADER_VIEW);
    
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    view.frame = RECT(0, 0, SCREEN_SIZE.width, _calculartorView.bottom);
    
    [view addSubview:self.toolbar];
    [view addSubview:_calculartorView];
    
    self.textField.inputAccessoryView = view;
}

#pragma mark -Calculator delegate

- (void)calculator:(CalculatorView *)view didPressedComput:(Compute)compute
{
    _calculartorView.state = TextFieldStateWaitingNewInput;
}

#pragma mark - TextField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    if (_calculartorView.state == TextFieldStateWaitingNewInput)
    {
        self.textField.text = string;
        _calculartorView.state = TextFieldStateInputing;
        
        return NO;
    }
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [super textFieldDidBeginEditing:textField];
    [_calculartorView startupWithResult:[textField floatValue]];
}

@end
